package com.squareshoot.picCheckin;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class PhotosAdapter extends ArrayAdapter<String> {
	int layout;
	Context context;
	ArrayList<String> photosList;

	PhotosDownloader photosDl;

	static class ViewHolder{
		ImageView photo;
		TextView venueName;
		TextView shout;
		TextView date;
	}

	public PhotosAdapter(Context context, ArrayList<String> objects) {
		super(context, R.layout.friendphotosadapter, objects);

		this.layout = R.layout.friendphotosadapter;
		this.context = context;
		this.photosList = objects;

		photosDl = new PhotosDownloader(false,true,getContext().getResources().getDrawable(R.drawable.loadingphoto));
	}

	public View getView(int position,View convertView,ViewGroup parent){
		ViewHolder holder;
		String checkin = photosList.get(position);
		JSONObject jCheckin;

		if(convertView==null){
			LayoutInflater inflater = LayoutInflater.from(context);
			convertView=inflater.inflate(layout, parent, false);

			holder = new ViewHolder();
			holder.photo = (ImageView) convertView.findViewById(R.id.friendPhoto);
			holder.venueName = (TextView) convertView.findViewById(R.id.friendPhotosVenue);
			holder.shout = (TextView) convertView.findViewById(R.id.friendPhotosShout);
			holder.date = (TextView) convertView.findViewById(R.id.friendPhotosDate);
			convertView.setTag(holder);
		}else{
			holder = (ViewHolder)convertView.getTag();
		}

		try {
			jCheckin = new JSONObject(checkin);

			photosDl.getPhoto(Common.getBaseImgsUrl()+jCheckin.getString("thumb"), holder.photo);

			holder.venueName.setText(jCheckin.getString("venuename"));

			if(jCheckin.has("shout")){
				holder.shout.setText(jCheckin.getString("shout"));
			}

			long millis = Long.parseLong(jCheckin.getString("millis"))*1000;
			Date date = new Date(millis);
			SimpleDateFormat formatter = new SimpleDateFormat("E, dd MMM kk:mm Z");
			holder.date.setText(formatter.format(date));
		} catch (JSONException e1) {
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"error JSON in PhotosAdapter : "+e1.getMessage());
		}

		return convertView;
	}
}
